package com.pig4cloud.mall.product.dto;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/11/30 8:59 下午
 */
@Data
public class QueryReq<T> {

	public IPage<T> getPage(PageParam param) {
		Map<String, Object> params = new HashMap<>();
		params.put("page", param.getCurrent());
		params.put("limit", param.getSize());
		return this.getPage(params);
	}

	public IPage<T> getPage(Page page) {
		Map<String, Object> params = new HashMap<>();
		params.put("page", page.getCurrent());
		params.put("limit", page.getSize());
		return this.getPage(params);
	}
	public IPage<T> getPage(Map<String, Object> params) {
		return this.getPage(params,null, false);
	}
	public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
		long currentPage = 1;
		long pageSize = 10;
		if (params.get("page") != null) {
			currentPage = (long) params.get("page");
		}

		if (params.get("limit") != null) {
			pageSize = (long) params.get("limit");
		}

		Page<T> page = new Page<>(currentPage, pageSize);

		// 没有排序字段，则不排序
		if (StringUtils.isBlank(defaultOrderField)) {
			return page;
		}

		if (isAsc) {
			page.addOrder(OrderItem.asc(defaultOrderField));
		} else {
			page.addOrder(OrderItem.desc(defaultOrderField));
		}

		return page;
	}
}
